package com.rocketmq.demo.base.producer;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: rocketmq-demo
 * @Package: com.rocketmq.demo.base.producer
 * @ClassName: SyncProducer
 * @Author: mac
 * @Description: 发送同步消息
 * @Date: 2021/3/30 2:21 下午
 * @Version: 1.0
 */
public class SyncProducer {

    public static void main(String[] args) {

        //1.创建消息生产者,并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group1");

        //2.指定NameService地址
        producer.setNamesrvAddr("192.168.31.67:9876;192.168.31.126:9876;192.168.31.209:9876");

        //3启动producer
        try {
            producer.start();

            //4.创建消息对象,指定Topic , Tag 和消息体
            for (int i = 0; i < 10; i++) {
                // 参数1:消息主题Topic 参数2:消息tag  参数3:消息类容
                Message msg = new Message("springboot-mq", "Tag1", ("hello world" + i).getBytes());

                //5.发送消息
                SendResult result = producer.send(msg);

                //发送状态
                SendStatus status = result.getSendStatus();

                System.out.println("发送结果:" + result.toString());
                System.out.println("发送状态:" + status.toString());

                TimeUnit.SECONDS.sleep(1);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.关闭消费者
            producer.shutdown();
        }
    }
}
